package com.nbicc.newpic.listener;

import com.nbicc.common.utils.ExceptionUtil;
import com.nbicc.newpic.processor.DeletePicByContentProcessor;
import com.nbicc.parent.Task;
import com.nbicc.parent.listener.OnDeleteListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lilingyan
 * 新闻删除监听器
 * 新闻删除时，只会立即删除文件元数据(news_info)  用户此时已无法查找到此新闻
 * 新闻内容中包含新闻图片信息（也需要一并删除），但会消耗大量时间(需解析)
 * 所有只把删除新闻的id放入新闻内容删除流的队列中
 */
@Slf4j
@Component("NewsContentDeleteListenerImpl")
public class NewsContentDeleteListenerImpl extends OnDeleteListener<Number>{

    @Autowired
    private DeletePicByContentProcessor  deletePicByContentProcessor;

    private Map<Number , Task> tasks = new HashMap<>();

    @Override
    public void delete(Number id , Task onCompletion) {
        try {
            tasks.put(id , onCompletion);
            deletePicByContentProcessor.putNewsId(id);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error(ExceptionUtil.getStackTraceInfo(e));
        }
    }

    public void onComplete(Number id) throws Exception {
        Task task = tasks.remove(id);
        if(task != null){
            task.run();
        }
    }

}
